﻿using System;
using System.Collections.Generic;
using System.Globalization;

namespace Globsite.Globalization.Mvc.DbResources
{
    public static class DbRes
    {
        private static readonly Dictionary<string, DbResourceManager> resourceManagers;

        static DbRes()
        {
            resourceManagers = new Dictionary<string, DbResourceManager>();
        }

        public static DbResourceManager GetResourceManager(string resourceSet)
        {
            // Resource set name should be unified if ignoring case is active.
            var ignoreCase = GlobsiteConfigSection.Instance.DbResources.IgnoreCase;
            if (ignoreCase)
                resourceSet = resourceSet.ToUpperInvariant();

            DbResourceManager resourceManager;
            if (!resourceManagers.TryGetValue(resourceSet, out resourceManager))
            {
                lock (resourceManagers)
                {
                    if (!resourceManagers.TryGetValue(resourceSet, out resourceManager))
                    {
                        resourceManager = new DbResourceManager(resourceSet)
                        {
                            IgnoreCase = ignoreCase
                        };
                        resourceManagers.Add(resourceSet, resourceManager);
                    }
                }
            }

            return resourceManager;
        }

        #region GetString

        public static string GetString(string resourceKey, string resourceSet, CultureInfo cultureInfo = null)
        {
            if (string.IsNullOrEmpty(resourceKey))
                throw new ArgumentNullException("resourceKey");

            // Get a resource value.
            var resourceManager = GetResourceManager(resourceSet);
            var resourceValue = resourceManager.GetString(resourceKey, cultureInfo);

            return resourceValue;
        }

        public static string GetString(string resourceKey, CultureInfo cultureInfo = null)
        {
            return GetString(resourceKey, string.Empty, cultureInfo);
        }

        public static string GetString(string resourceKey, string resourceSet, string cultureName)
        {
            return GetString(resourceKey, resourceSet, CultureInfo.CreateSpecificCulture(cultureName));
        }

        #endregion
    }
}